import store from '@/store/index.js'
import { exitAndClear, disconnectIMService } from '@/store/dispatches.js';

const getUrlQuery = (url = '', variable) => {
	if (!url) {
		return false;
	}
	const urlArray = url.split('?');
	const query = urlArray.length < 2 ? urlArray[0] : urlArray[1];
	const vars = query.split("&");
	for (var i = 0; i < vars.length; i++) {
		const pair = vars[i].split('=');
		if (pair[0] == variable) {
			return pair[1];
		}
	}
	return false;
}

/**
 * px转rpx
 */
const px2rpx = (num) => {
	return num / (uni.upx2px(100) / 100);

}

const getPlatform = () => {
	const systemInfo = uni.getSystemInfoSync();
	const platform = systemInfo.platform;
	return {
		ios: 'ios' == platform,
		android: 'android' == platform
	}
}

const isWechat = () => {
	// #ifdef H5
	let ua = window.navigator.userAgent.toLowerCase();
	if (ua.match(/MicroMessenger/i) == 'micromessenger') {
		return true; // 是微信端
	} else {
		return false;
	}
	// #endif
	// #ifndef H5
	return false;
	// #endif

};

/**
 * 获取底部安全距离
 */
const getSafeAreaBottomHeight = () => {
	const systemInfo = uni.getSystemInfoSync();
	console.log(systemInfo)
	return systemInfo.windowHeight + (systemInfo.windowTop || 0) - systemInfo.safeArea.top - systemInfo.safeArea.height;
}
/**
 * 获取场景值(scene)
 */
const getSceneData = (query) => {
	return query.scene ? scene_decode(query) : query;
};
/**
 * 富文本处理(html)
 */
const formatRichText = (html) => {
	let newContent = html.replace(/<img[^>]*>/gi, function(match, capture) {
		match = match.replace(/style="[^"]+"/gi, '').replace(/style='[^']+'/gi, '');
		match = match.replace(/width="[^"]+"/gi, '').replace(/width='[^']+'/gi, '');
		match = match.replace(/height="[^"]+"/gi, '').replace(/height='[^']+'/gi, '');
		return match;
	});
	newContent = newContent.replace(/style="[^"]+"/gi, function(match, capture) {
		match = match.replace(/width:[^;]+;/gi, 'max-width:100%;').replace(/width:[^;]+;/gi, 'max-width:100%;');
		return match;
	});
	newContent = newContent.replace(/<br[^>]*\/>/gi, '');
	// newContent = newContent.replace(/\<img/gi, '<img style="max-width:100%;height:auto;display:block;margin-top:0;margin-bottom:0;"');
	return newContent;
};

/**
 * 切换首页选项卡项目
 */

const switchTabber = (role = 10) => {
	// #ifndef MP-TOUTIAO
	uni.setTabBarItem({
		index: 0,
		text: role == 10 ? '穗穗' : '单身团',
		iconPath: '/static/images/tab/' + (role == 10 ? 'card' : 'matchmaker') + '-default.png',
		selectedIconPath: '/static/images/tab/' + (role == 10 ? 'card' : 'matchmaker') + '-selected.png',
	})
	// #endif

}
/**
 * 手机号码隐私化
 */

const phoneNumberProtection = (tel, frontLen = 3, endLen = 4) => {
	tel = String(tel);
	const len = tel.length - frontLen - endLen;
	var start = '';
	for (var i = 0; i < len; i++) {
		start += '*';
	}
	return tel.substring(0, frontLen) + start + tel.substring(tel.length - endLen);
}


/**
 * 是否在数组内
 */
const inArray = (search, array) => {
	for (var i in array) {
		if (array[i] == search) {
			return true;
		}
	}
	return false;
};
/**
 * 显示失败提示框
 */
const showError = (msg, callback) => {
	uni.showModal({
		title: '友情提示',
		content: msg,
		showCancel: false,
		success(res) {
			// callback && (setTimeout(function() {
			//   callback();
			// }, 1500));
			callback && callback();
		}
	});
}


/**
 * 显示成功提示框
 */
const showSuccess = (msg, callback) => {
	uni.showToast({
		title: msg,
		icon: 'success',
		mask: true,
		duration: 1500,
		success() {
			callback && (setTimeout(function() {
				callback();
			}, 1500));
		}
	});
};

/**
 * 验证登录
 */
const checkIsLogin = () => {
	return store.state.user.token || false;
};

/**
 *  用正则表达式实现html编码（转义）
 */
const html2Escape = (html) => {
	return html.replace(/[<>&"]/g, function(c) {
		return {
			'<': '&lt;',
			'>': '&gt;',
			'&': '&amp;',
			'"': '&quot;'
		} [c];
	});
};
/**
 *  用正则表达式实现html解码（反转义）
 */
const escape2Html = (str) => {
	var arrEntities = {
		'lt': '<',
		'gt': '>',
		'nbsp': ' ',
		'amp': '&',
		'quot': '"'
	};
	return str.replace(/&(lt|gt|nbsp|amp|quot);/ig, function(all, t) {
		return arrEntities[t];
	});
}

const formatSize = (limit) => {
	let size = '';
	if (limit < 0.1 * 1024) { //小于0.1KB，则转化成B
		size = limit.toFixed(2) + "B"
	} else if (limit < 0.1 * 1024 * 1024) { //小于0.1MB，则转化成KB
		size = (limit / 1024).toFixed(2) + "KB"
	} else if (limit < 0.1 * 1024 * 1024 * 1024) { //小于0.1GB，则转化成MB
		size = (limit / (1024 * 1024)).toFixed(2) + "MB"
	} else { //其他转化成GB
		size = (limit / (1024 * 1024 * 1024)).toFixed(2) + "GB"
	}

	const sizeStr = size + ""; //转成字符串
	const index = sizeStr.indexOf("."); //获取小数点处的索引
	const dou = sizeStr.substr(index + 1, 2) //获取小数点后两位的值
	if (dou == "00") { //判断后两位是否为00，如果是则删除00
		return sizeStr.substring(0, index) + sizeStr.substr(index + 3, 2)
	}
	return size;
}

const logout = () => {
	return new Promise((resolve, reject) => {
		uni.showLoading({
			title: '请稍候...'
		})
		exitAndClear();
		disconnectIMService()
		setTimeout(() => {
			uni.hideLoading()
			resolve()
		}, 700)
	})
}

const toLoginPage = () => {
	uni.navigateTo({
		url: !isWechat() ? '/pageUser/login/member' : '/pageUser/login/index'
	})
}


export default {
	px2rpx,
	getPlatform,
	isWechat,
	getSafeAreaBottomHeight,
	getSceneData,
	formatRichText,
	switchTabber,
	phoneNumberProtection,
	inArray,
	showError,
	showSuccess,
	getUrlQuery,
	checkIsLogin,
	html2Escape,
	escape2Html,
	formatSize,
	logout,
	toLoginPage
}
